package com.qf.quduba.config;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author 17312
 * @time2020/9/2220:33
 */
@Component
@ServerEndpoint("/webSocket/{rechargeId}")
public class WebSocket {
    private static ConcurrentMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    //跳转至支付页面，等待支付
    @OnOpen
    public void open (@PathParam("rechargeId")String rechargeId,Session session){
        sessionMap.put(rechargeId,session);
    }

    //关闭支付页面
    @OnClose
    public void close(@PathParam("rechargeId")String rechargeId ){
        sessionMap.remove(rechargeId);
    }
    //推送消息
    public static void sendMsg(String msg,String rechargeId){
        try {
            Session session = sessionMap.get(rechargeId);
            if(session != null){
                session.getBasicRemote().sendText(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
